﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using M7;
using System.Threading;

namespace S7
{
    public static class ChatServer
    {
        private static List<ChatClient> _ChatMsgs;

        public static List<ChatClient> ChatMsgs
        {
            get { return ChatServer._ChatMsgs; }
            set { ChatServer._ChatMsgs = value; }
        }

        public static bool IsRunning = false;
        public static Dictionary<IPAddress, ChatClient> clients = new Dictionary<IPAddress, ChatClient>();
        public static int NumberOfClients = 0;

        public static void Start()
        {
            IsRunning = true;
        }
        public static void Stop()
        {
            IsRunning = false;
            clients = null;
        }

        public static bool AddClient(ChatClient c)
        {
            if (!clients.ContainsKey(c.ip))
            {
                clients.Add(c.ip, c);
                return true;
            }
            else
            {
                return false;
            }
        }
        public static bool RemoveClient(ChatClient c)
        {
            if (clients.ContainsKey(c.ip))
            {
                clients.Remove(c.ip);
                return true;
            }
            else
            {
                return false;
            }
        }
        public static bool SendToClients(ChatClient c)
        {
            Info.window.Dispatcher.Invoke(new ThreadStart(() =>
                {
                    foreach (var table in Info.window.wrpLiveView.Children.OfType<TableControl>())
                    {
                        if (table.Connection != null)
                        {
                            Msg SendMsg = new Msg();
                            SendMsg.enumMethod = enumChat.ChatReceiveMsg;
                            SendMsg.obj = c;
                            SendMsg.IP = table.Connection.current.IP;
                            SendMsg.port = table.Connection.current.Port;
                            Info.server.SendingQueue.Enqueue(SendMsg);
                        }
                    }
                }));
                return true;
        }
    }
}
